package com.sanjiahantang.youjiaclient.module.common.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.sanjiahantang.uilibrary.R;
import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.common.beans.FileBean;
import com.sanjiahantang.youjiaclient.module.common.beans.MeIcon;
import com.sanjiahantang.youjiaclient.module.common.beans.MessageNoticeCountBean;
import com.sanjiahantang.youjiaclient.module.common.beans.UserBean;
import com.sanjiahantang.youjiaclient.module.common.models.IFileModel;
import com.sanjiahantang.youjiaclient.module.common.models.IUserModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.FileModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiaclient.module.common.views.MeView;
import com.sanjiahantang.youjiaclient.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiaclient.module.login.views.impl.RegisterActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.MessageActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.SettingsActivity;
import com.sanjiahantang.youjiaclient.module.complain.views.impl.MeComplainActivity;
import com.sanjiahantang.youjiaclient.module.evaluate.views.impl.MeEvaluateActivity;
import com.sanjiahantang.youjiaclient.module.me.account.views.impl.AccountActivity;
import com.sanjiahantang.youjiaclient.module.me.contract.views.impl.ContractActivity;
import com.sanjiahantang.youjiaclient.module.me.favorite.views.impl.FavoriteActivity;
import com.sanjiahantang.youjiaclient.module.me.help.HelpCenterActivity;
import com.sanjiahantang.youjiaclient.module.me.order.views.impl.MyOrderActivity;
import com.sanjiahantang.youjiaclient.module.me.require.views.impl.RequireListActivity;
import com.sanjiahantang.youjiaclient.module.me.scheme.views.impl.MeSchemeActivity;
import com.sanjiahantang.youjiaclient.module.me.scheme.views.impl.MeSchemeActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramOrderActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramPriceActivity;
import com.sanjiahantang.youjiaclient.utils.SPUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import q.rorbin.badgeview.QBadgeView;

/**
 * Created by zy on 2017/9/4.
 */

public class MePresenter extends BaseMvpPresenter<MeView>  {
    private QuickAdapter<MeIcon> mQuickAdapter;

    private MeIcon miBean;
    private String[] items = {"待付款", "部分付款", "已付款", "已完成"};
    private int[] icons = {R.drawable.i_wait_payment, R.drawable.i_wait_deliver,
            R.drawable.i_wait_receive, R.drawable.i_after_sale};
    private IUserModel userModel;
    private IFileModel fileModel;

    final int PHOTO_GRAPH = 2, SELECT_PICTURE = 3, INTENT_NICKNAME = 5, SAVE_PHOTO = 6;
    public static String filePath = "";
    private Uri imageUri;

    public MePresenter(){
        userModel = new UserModel();
        fileModel = new FileModel();
    }

    public QuickAdapter<MeIcon> initGridAdapter(BaseMvpActivity context){
        ArrayList<MeIcon> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miBean = new MeIcon();
            miBean.setItems(items[i]);
            miBean.setIcon(icons[i]);
            list.add(miBean);
        }

        mQuickAdapter = new QuickAdapter<MeIcon>(context, R.layout.item_me_icon) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIcon item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                            .setGravityOffset(-2,-2, true)
                            .setBadgeTextSize(8, true);
                }
            }
        };

        mQuickAdapter.addAll(list);
        return mQuickAdapter;
    }





    public boolean network(final BaseMvpActivity activity) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(activity)) {
            Utils.showDialog(activity, "提示", "您现在的网络不是太好哦！", "", "重试", new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    Utils.dismissDialog();
                    switch (view.getId()) {
                        case R.id.txtDialogCancel:
                            break;
                        case R.id.txtDialogSure:
                            initUserData(activity);
                            break;
                    }
                }
            });
            return false;
        }
        return true;
    }

    public void toLogin(BaseMvpActivity context) {
        LoginActivity.logout(context);
    }

    private void initUserData(BaseMvpActivity context) {
        ConfigValue.DATA_KEY = (String) SPUtils.get(context, SPConfig.KEY, "");
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            Map<String,String> params = new HashMap<>();
            params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
            params.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
            mView.showProgress();
            userModel.dopersonData(context, params, new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean response, Context context, Object tag) {
                    hideProgress();
                    if (response != null){
                        String message = response.getMessage();
                        if (response.getCode() == RESPONSE_CODE_SUC && response.getData().getUserDto() != null) {
                            showInfo(context,response.getData().getUserDto());
                        }else {
                            SPUtils.remove(context, SPConfig.KEY);
                            Utils.showToast(context, message);
                        }
                    }
                }

                @Override
                public void onFailure(String message) {
                    mView.hideProgress();
                }
            });
        } else {
            mView.changeUIToLogout();
        }
    }

    private QuickAdapter<MeIcon> initGrid(BaseMvpActivity context) {
        ArrayList<MeIcon> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miBean = new MeIcon();
            miBean.setItems(items[i]);
            miBean.setIcon(icons[i]);
            list.add(miBean);
        }


        mQuickAdapter= new QuickAdapter<MeIcon>(context, R.layout.item_me_icon) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIcon item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                            .setGravityOffset(-2,-2, true)
                            .setBadgeTextSize(8, true);
                }

            }
        };
        mQuickAdapter.addAll(list);
        return mQuickAdapter;
    }

    private void goPageByType(BaseMvpActivity context, int position, Class toPage) {
        Intent intent = new Intent(context, toPage);
        intent.putExtra("type", position);
        context.startActivity(intent);
    }



    public void onItemClick(BaseMvpActivity context, int type1, int type2) {
        if (network(context)) {
            if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
                Intent intent = new Intent(context,MyOrderActivity.class);
                intent.putExtra("type1",type1);
                intent.putExtra("type2",type2);
                context.startActivity(intent);
            } else {
                toLogin(context);
            }
        }
    }

    private void goPageCheckNet(BaseMvpActivity context,Class toPage){
        if (network(context)) {
            goPageSimply(context,toPage);
        }
    }

    private void goPageCheckNetAndLogin(BaseMvpActivity context,Class toPage){
        if (network(context)) {
            if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
                goPageSimply(context,toPage);
            } else{
                toLogin(context);
            }
        }
    }

    public void goMessagePage(BaseMvpActivity context) {
        goPageCheckNetAndLogin(context,MessageActivity.class);
    }

    public void goAccountPage(BaseMvpActivity context) {
        goPageCheckNet(context,AccountActivity.class);
    }

    public void goRegisterPage(BaseMvpActivity context) {
        goPageSimply(context,RegisterActivity.class);
    }

    public void goDecorateManagerPage(BaseMvpActivity context) {
        ((MainActivity)context).setFragmentIndex(1);
    }

    public void goHelpCenter(BaseMvpActivity context) {
        Intent intent = new Intent(context, HelpCenterActivity.class);
        context.startActivity(intent);
    }

    public void goSchemePage(BaseMvpActivity context) {
        goPageCheckNetAndLogin(context,MeSchemeActivity.class);
//        Intent intent = new Intent(context, ProgramOrderActivity.class);
//        context.startActivity(intent);
    }

    public void goAllOrderPage(BaseMvpActivity context) {
        goPageCheckNetAndLogin(context,MyOrderActivity.class);
    }

    public void goFavoritePage(BaseMvpActivity context) {
        goPageCheckNetAndLogin(context,FavoriteActivity.class);
    }

    public void goContractPage(BaseMvpActivity context) {
        goPageSimply(context,ContractActivity.class);
    }


    /**
     * 我的评价
     * @param context
     */
    public void goEvaluatePage(BaseMvpActivity context) {
        goPageSimply(context,MeEvaluateActivity.class);
    }

    public void goSettingsPage(BaseMvpActivity context) {
        goPageSimply(context,SettingsActivity.class);
    }



    public void goCSDPage(BaseMvpActivity context) {
        goPageCheckNetAndLogin(context,MeComplainActivity.class);
    }

    private void showInfo(Context context,UserBean.Item userInfo) {
        ConfigValue.userInfo = userInfo;
        if (userInfo == null || userInfo.getPhone() == null ) return;
        mView.changeUIToLogin(userInfo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        if (!TextUtils.isEmpty(userInfo.getQrCode())){
            SPUtils.put(context,SPConfig.QR_CODE,userInfo.getQrCode());
        }

        ArrayList<MeIcon> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miBean = new MeIcon();
            miBean.setItems(items[i]);
            miBean.setIcon(icons[i]);
            switch (i) {
                case 0:
//                    miBean.setNum(ConfigValue.userInfo.getPay());
                    break;
                case 1:
//                    miBean.setNum(ConfigValue.userInfo.getShipping_send());
                    break;
                case 2:
//                    miBean.setNum(ConfigValue.userInfo.getShipping());
                    break;
                case 3:
//                    miBean.setNum(ConfigValue.userInfo.getFinished());
                    break;
            }
            list.add(miBean);
        }

        if(mQuickAdapter == null){
            mQuickAdapter= new QuickAdapter<MeIcon>(context, R.layout.item_me_icon) {
                @Override
                protected void convert(BaseAdapterHelper helper, MeIcon item) {
                    helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                    helper.setText(R.id.txtItem, item.getItems());
                    ImageView orderType = helper.getView(R.id.imgIcon);



                    if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                        new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                                .setBadgeNumber(Integer.valueOf(item.getNum()))
                                .setGravityOffset(-2,-2, true)
                                .setBadgeTextSize(8, true);
                    }

                }
            };
        }
        mQuickAdapter.clear();
        mQuickAdapter.addAll(list);
        mView.reloadGridAdapter(mQuickAdapter);
    }



    private void hideProgress() {
        if (mView != null) mView.hideProgress();
    }



    public void onLoad(BaseMvpActivity context) {
        if(TextUtils.isEmpty(ConfigValue.DATA_KEY)){
            mView.changeUIToLogout();
        }else if(ConfigValue.userInfo == null){
            initUserData(context);
        }else{
            showInfo(context,ConfigValue.userInfo);
        }
    }

    private Uri convertUri(Context context,Uri uri) {
        InputStream is = null;
        try {
            is = context.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(context,bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Uri saveBitmap(Context context,Bitmap bm) {
        File tmpDir = new File(Environment.getExternalStorageDirectory()
                + "/");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        File img = new File(tmpDir.getAbsolutePath() + "/head.jpg");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            Toast.makeText(context, "成功了", Toast.LENGTH_SHORT).show();

            return FileProvider.getUriForFile(
                    context,
                    context.getPackageName() + ".provider",
                    img);
        } catch (FileNotFoundException e) {
            Toast.makeText(context, "失敗了", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "失敗了", Toast.LENGTH_SHORT).show();
            return null;
        }

    }

    //相机拍照获取图片
    public void takePictures(Activity activity) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File("/sdcard/");
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, "head.jpg");
            Uri photoUri = FileProvider.getUriForFile(
                    activity,
                    activity.getPackageName() + ".provider",
                    file);
            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

            filePath = file.getAbsolutePath();
            imageUri = Uri.fromFile(file);

            activity.startActivityForResult(takePhotoIntent, PHOTO_GRAPH);
        } else
            Toast.makeText(activity, "未插入SD卡", Toast.LENGTH_SHORT).show();
    }

    public void cardSelect(Activity activity) {
        Intent it = new Intent(Intent.ACTION_PICK);
        it.setType("image/*");
        activity.startActivityForResult(it, SELECT_PICTURE);
    }


    public void onActivityResult(Context context,int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK){
            switch (requestCode){
                case PHOTO_GRAPH:
                    startImageAction(context,imageUri, 320, 320,
                            SAVE_PHOTO, true);
                    break;
                case SELECT_PICTURE:
                    startImageAction(context,data.getData(), 320, 320,
                            SAVE_PHOTO, true);
                    break;
                case SAVE_PHOTO:

                    if (data == null)
                        return;
                    else
                        Utils.showToast(context,"保存");
                        showPhoto(context,data);
                        filePath = "";
                    break;
            }
        }
    }

    public void showPhoto(Context context,Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            if (bitmap != null) {
              // headPhoto.setImageBitmap(bitmap);
              String  filed_id=SPUtils.get(context,SPConfig.FILD_ID,"").toString();
                doUpload(context,bitmap,filed_id);
                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        }else if(data.getData() != null){
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void doUpload(Context context, Bitmap bitmap,String filed_id) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_FILE_ID,filed_id);
        param.put(KEY_BUSINESS_ID,SPUtils.get(context,SPConfig.PHONE,"").toString());
        param.put(KEY_BUSINESS_TYPE_ID,"customerHeadPic");
        param.put(KEY_FILE_NAME,"head.jpg");
        param.put(KEY_FILE_BASE64_PIC,Utils.bitmapToBase64(bitmap));
        fileModel.doUpoad(context,param, new CallBack<FileBean>() {
            @Override
            public void onSuccess(FileBean response, Context context, Object tag) {
                if (response.getCode()==RESPONSE_CODE_SUC){
                    Utils.showToast(context,"头像上传成功");
                }
            }
            @Override
            public void onFailure(String message) {

            }
        });
    }

    /**
     * 剪裁照片，并将剪裁之后的照片存在imageUri中，照片的名称问newhead.jpg,若提交更改，则将newhead.jpg重命名为head.jpg
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     * @param isCrop
     */
    public void startImageAction(Context context, Uri uri, int outputX, int outputY,
                                 int requestCode, boolean isCrop) {

        Intent intent = null;
        if (isCrop) {
            intent = new Intent("com.android.camera.action.CROP");
        } else {
            intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        }
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(Environment.getDownloadCacheDirectory() + "/" + (new File(uri.getPath())).getName());

            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", outputX);
            intent.putExtra("outputY", outputY);
            intent.putExtra("scale", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            intent.putExtra("return-data", true);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("noFaceDetection", true); // no face detection
            ((Activity)context).startActivityForResult(intent, requestCode);
        }

    }

    public void goRequirePage(Context context) {
        goPageSimply(context, RequireListActivity.class);
    }

    public void getSearchNoticeCountForCustomer(Context context, final BaseView.OnLoadListener listener) {
        Map<String,String> map=new HashMap<>();
        String phone = SPUtils.get(context, SPConfig.PHONE,"").toString();
        map.put("customerPhone",phone);
        map.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        userModel.getSearchNoticeCountForCustomer(context, map, new CallBack<MessageNoticeCountBean>() {
            @Override
            public void onSuccess(MessageNoticeCountBean response, Context context, Object tag) {
                if (response != null && response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(response.getData());
                }else{
                    listener.onLoad(null);
                }
            }

            @Override
            public void onFailure(String message) {
                listener.onLoad(null);
            }
        });
    }

    public void doUpload(final Context context, Uri uri, final BaseView.OnLoadListener listener) {
        mView.showProgress();
        Bitmap bitmap = null;
        new File(uri.toString());
        try {
            bitmap = Utils.getBitmapFormUri((Activity) context,uri);
            doUpload(context,bitmap,listener);
        } catch (IOException e) {
            e.printStackTrace();
            if (mView == null) return;
            mView.hideProgress();
        }

    }

    public void doUpload(final Context context, Bitmap bitmap, final BaseView.OnLoadListener listener) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_FILE_ID,ConfigValue.userInfo.getFileId() == null ? "0" : ConfigValue.userInfo.getFileId());
        param.put(KEY_BUSINESS_ID,SPUtils.get(context,SPConfig.PHONE,"").toString());
        param.put(KEY_BUSINESS_TYPE_ID,"customerHeadPic");
        param.put(KEY_FILE_NAME,"head.jpg");
        param.put(KEY_FILE_BASE64_PIC, Utils.bitmapToBase64(bitmap));
        fileModel.doUpoad(context,param, new CallBack<FileBean>() {
            @Override
            public void onSuccess(FileBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC){
                    Utils.showToast(context,"上传成功");
                    listener.onLoad(response.getData());
                }else{
                    Utils.showToast(context,"上传失败");
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context,"上传失败");
            }
        });

    }
}
